<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2023-09-21 15:00:32
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-09-21 15:03:45
 */


declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace Common\Core;


use Common\Component\Singleton;
use Common\Exception\BaseException;
use Common\Helpers\DebugHelper;
use FastRoute\Dispatcher;
use Hyperf\Contract\ContainerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Router\DispatcherFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 调度运行游戏逻辑策略,分别调度到不同协议目录里，策略模式容器.
 */
class WebsocketCore
{
    use Singleton;

    /**
     * 执行结果
     * @var array
     */
    private array $_strategy;

    /**
     * 参数配置文件.
     * @var array
     */
    private array $_params = [];

    /**
     * @Inject(ContainerInterface::class)
     * @var ContainerInterface
     */
    #[Inject]
    protected ContainerInterface $container;

    /**
     * @Inject(DispatcherFactory::class)
     * @var DispatcherFactory
     */
    #[Inject]
    protected DispatcherFactory $dispatcherFactory;


    public function __construct($params)
    {
        $this->_params = $params;
        $this->Strategy();
    }


    /**
     * 调度处理
     */
    public function Strategy(): void
    {
        $params = $this->_params;
        // 创建路由分发器
        $dispatcher = $this->dispatcherFactory->getDispatcher('ws');
        if(empty($params['addons'])){
            $this->_strategy  = [
                'code'=>401,
                'message'=>'addons不能为空'
            ];
            return;
        }
        if(empty($params['controller'])){
            $this->_strategy  =  [
                'code'=>401,
                'message'=>'controller不能为空'
            ];
            return;
        }
        if(empty($params['action'])){
            $this->_strategy  =  [
                'code'=>401,
                'message'=>'action不能为空'
            ];
            return;
        }
        $path = "/".strtolower($params['addons'])."/".strtolower($params['controller'])."/".strtolower($params['action']);
        DebugHelper::consoleWrite('路由分发-路径',$path);
        // 解析 WebSocket 请求的路由信息
        $routeInfo = $dispatcher->dispatch('GET',$path);
        var_dump($routeInfo);
        /**
         * 获取websocket请求的路由信息
         */


        DebugHelper::consoleWrite('路由分发',[
            $routeInfo,
            $path,
            $routeInfo[1]->callback
        ]);

        if ($routeInfo[0] === Dispatcher::FOUND) {
            // 找到匹配的路由并执行对应的处理逻辑
            $handler = $routeInfo[1];
            try {
                if (is_string($handler->callback) && str_contains($handler->callback, '@')) {
                    [$controller, $action] = explode('@', $handler->callback, 2);
                } else if (is_string($handler->callback) && !str_contains($handler->callback, '@')) {
                    $controller = $handler->callback;
                    $action = 'index';
                }else if (is_array($handler->callback)) {
                    [$controller, $action]  = $handler->callback;
                }
                DebugHelper::consoleWrite('分发结果',[
                    'controller'=> $controller,
                    'action'=>$action
                ]);
                $controllerInstance = $this->container->make($controller);
                $response = $controllerInstance->$action($params);
//                $response = (new $controller($request, $response, $this->logger, $this->dispatcherFactory, $this->sender, $this->container))->$action($params['param']);
                $this->_strategy = $response;
            } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
                throw new BaseException(401,$e->getMessage());
            }
        } else {
            $this->_strategy = [
                'code'=>401,
                'type'=>'error',
                'message'=>'路由不存在'.$path
            ];
        }
    }

    /**
     * 获取策略.
     */
    public function getStrategy(): string
    {
        return json_encode($this->_strategy,JSON_UNESCAPED_UNICODE);
    }
}
